package com.frinder.demo.delimiter;

import com.frinder.base.client.AbstractClient;
import com.frinder.base.client.ClientMessageAdapter;
import com.frinder.base.client.ConnectionWatchDog;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static com.frinder.base.ByteBufUtils.buf;
import static com.frinder.base.ByteBufUtils.str;
import static com.frinder.demo.delimiter.DelimiterUtils.DELIMITER;

/**
 * @ClassName DelimiterClient
 * @Description 基于消息边界方式
 * @Author frinder
 * @Date 2019/4/16 13:46
 * @Verion 1.0
 */
@Slf4j
public class DelimiterClient extends AbstractClient {

    public static void main(String[] args) throws IOException {
        DelimiterClient client = new DelimiterClient("127.0.0.1", 8888);
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String message;
        while (true) {
            message = in.readLine();
            if ("s".equalsIgnoreCase(message)) {
                client.destroy();
                return;
            }
            client.send(buf(message, DELIMITER));
        }
    }

    public DelimiterClient(String host, int port) {
        super("delimiter", host, port);
        super.start();
    }

    @Override
    protected ConnectionWatchDog getConnectionWatchDog() {
        return new ConnectionWatchDog(this, true) {
            @Override
            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        // 重连机制
                        this,
                        // 日志处理器
                        new LoggingHandler(LogLevel.WARN),
                        // 解码器
                        DelimiterUtils.decoder(),
                        // 消息过滤器
                        new ClientMessageAdapter(),
                        // 消息处理机制
                        new DelimiterClientHandler()
                };
            }
        };
    }

    class DelimiterClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) {
            log.info("*** >> 客户端接收消息：{}", str(buf));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    }
}
